import {
  _decorator,
  animation,
  AnimationClip,
  Animation,
  Component,
  Sprite,
  SpriteFrame,
  UITransform,
  Node,
  EventTouch,
} from 'cc'
import { createUINode } from '../Utils/UtilsIndex'
import GameData, { DataMgr } from '../Runtime/GameData'
import ResourceManager from '../Runtime/ResourceManager'
import { CONTROLLER_PLAYER, GAME_EVENT_ENUM } from '../Config/Enums/EnumsIndex'
import EventManager from '../Runtime/EventManager'
const { ccclass, property } = _decorator
const ANIMATION_SPEED = 1 / 8

@ccclass('PlayerManager')
export class PlayerManager extends Component {
  /** 移动事件节点点击*/
  @property(Node)
  moveUP: Node = null
  @property(Node)
  moveDOWN: Node = null
  @property(Node)
  moveLEFT: Node = null
  @property(Node)
  moveRIGHT: Node = null
  //移动目标
  targetX:number = 0;
  targetY:number = 0;
  //实际位置
  x:number = 0;
  y:number = 0;
  speed = 1/10;

  move_position = -1;
  async init() {
    try {
      const playerAnimNode = createUINode('playerAnim')
      this.node.addChild(playerAnimNode)
      await this.renderPlayer(playerAnimNode)
    } catch (error) {
      console.error('Error loading PlayerManager AnimationClip:', error)
    }
    /**注册人物移动事件监听 */
    EventManager.Instance.on(GAME_EVENT_ENUM.PlayerMove, this.move,this)
    /**注册点击事件 */
    this.moveUP.on(Node.EventType.TOUCH_END, () => {
    })
  }
  async renderPlayer(playerAnimNode: Node) {
    playerAnimNode.addComponent(Animation)

    //为node添加组件
    const sprite = playerAnimNode.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM

    /**设置尺寸大小 */
    const transform = playerAnimNode.getComponent(UITransform)
    transform.setContentSize(DataMgr.TILE_WIDTH * 4, DataMgr.TILE_HEIGHT * 4)

    // 加载图片
    const spriteFrames = await ResourceManager.Instance.loadResAtlasAsync('texture/player/idle/top/idle')

    playerAnimNode.getComponent(Sprite).spriteFrame = spriteFrames[0]
    const animationComponent = playerAnimNode.getComponent(Animation)

    const animationClip = new AnimationClip()
    animationClip.duration = 1.0 // 整个动画剪辑的周期

    const track = new animation.ObjectTrack() // 创建一个对象轨道

    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame') // 指定轨道路径
    const frames: Array<[number, SpriteFrame]> = []
    spriteFrames.getSpriteFrames().forEach((spriteFrame, index) => {
      frames.push([ANIMATION_SPEED * index, spriteFrame])
    })
    track.channel.curve.assignSorted(frames) // 添加关键帧，指定时间点和对应的值
    // 最后将轨道添加到动画剪辑以应用
    animationClip.addTrack(track)

    animationClip.duration = ANIMATION_SPEED * spriteFrames.getSpriteFrames().length // 设置动画剪辑的周期，即动画的总时长
    animationClip.name = 'idle' // 设置动画剪辑的名称
    animationClip.wrapMode = AnimationClip.WrapMode.Loop // 设置动画剪辑的循环模式

    animationComponent.defaultClip = animationClip // 将动画剪辑设置为默认剪辑

    animationComponent.play('idle') // 播放动画

    /**获取动画播放状态 */
    const state = animationComponent.getState('idle')
    if (!state) {
      console.error('Failed to get animation state for "idle".')
    }
  }
  /**人物移动 */
  move(inputDirection:CONTROLLER_PLAYER) {
    switch (inputDirection) {
      case CONTROLLER_PLAYER.UP:
        this.targetX+=1;
        break;
      case CONTROLLER_PLAYER.DOWN:
        this.targetX-=1;
        break;
      case CONTROLLER_PLAYER.LEFT:
        this.targetY-=1;
        break;
      case CONTROLLER_PLAYER.RIGHT:
        this.targetY+=1;
        break;

    }
  }
  updateXY(){
    if(this.targetX<this.x){
      this.x-=this.speed;
    }
    else if(this.targetX>this.x){
      this.x+=this.speed;
    }
    if(this.targetY<this.y){
      this.y-=this.speed;
    }
    else if(this.targetY>this.y){
      this.y+=this.speed;
    }
    if(Math.abs(this.targetX-this.x)<=0.1 && Math.abs(this.targetY-this.y)<=0.1){
      this.targetX=this.x;
      this.targetY=this.y;
    }
  }

  update(dt: number) {
    this.updateXY;
    this.node.setPosition(this.x*DataMgr.TILE_WIDTH - 1.5*DataMgr.TILE_WIDTH,-this.y*DataMgr.TILE_HEIGHT + 1.5*DataMgr.TILE_HEIGHT)

  }
}
